package com.itheima.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.common.models.AlipayTradeRefundResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("easy/")
public class EasyController {

    @Autowired
    Config config;

    @GetMapping("pay/{code}")
    public String pay(@PathVariable String code) {

        Factory.setOptions(config);

        try {
            AlipayTradePrecreateResponse response = Factory.Payment.FaceToFace()
                    .preCreate("惨惨惨", code, "0.01");
            if(ResponseChecker.success(response)){
                String httpBody = response.getHttpBody();
                System.out.println(httpBody);
                return httpBody;
            }else{
                System.out.println("失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

    // 查询支付状态
    @GetMapping("querypay/{code}")
    public String querypay(@PathVariable String code) {
        Factory.setOptions(config);

        try {
            AlipayTradeQueryResponse response = Factory.Payment.Common().query(code);

            Map<String, Map<String, String>> map = JSON.parseObject(response.getHttpBody(), Map.class);
            if (map.get("alipay_trade_query_response").get("trade_status").equals("TRADE_SUCCESS")) {
                System.out.println("支付成功......");
                System.out.println("处理订单后续操作.....");
            }

            return response.getHttpBody();

        } catch (Exception e) {
            System.err.println("调用遭遇异常，原因：" + e.getMessage());
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    @GetMapping("refund/{code}")
    public String refund(@PathVariable String code){
        Factory.setOptions(config);

        try {
            AlipayTradeRefundResponse response = Factory.Payment.Common().refund(code, "0.01");


            return response.getHttpBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "ERROR";
    }

}

